package cn.shopthrive.merchants;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

import androidx.core.content.ContextCompat;

import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.flutter.embedding.engine.FlutterEngine;
import io.flutter.plugin.common.MethodChannel;

public class WeChatHelper {
  private static final String APP_ID = "wx111a6ee438a3e70e";
  private static final String CHANNEL = "com.shopthrive.merchants/wechat";
  private static IWXAPI api;
  private static MethodChannel channel;
  private static BroadcastReceiver weChatReceiver;
  private static BroadcastReceiver refreshReceiver;

  public static void init(Context context, MethodChannel weChatChannel) {
    Log.i("WeChatHelper", "init: 开始初始化");
    if (api == null) {
      api = WXAPIFactory.createWXAPI(context, APP_ID, true);
      api.registerApp(APP_ID);
      Log.i("WeChatHelper", "init: 创建并注册微信API");
    }
    channel = weChatChannel; // 使用传入的 MethodChannel
    if (refreshReceiver == null) {
      refreshReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          Log.i("WeChatHelper", "refreshReceiver: 重新注册微信应用");
          api.registerApp(APP_ID);
        }
      };
      IntentFilter refreshFilter = new IntentFilter("com.tencent.mm.plugin.openapi.Intent.ACTION_REFRESH_WXAPP");
      ContextCompat.registerReceiver(context, refreshReceiver, refreshFilter, ContextCompat.RECEIVER_NOT_EXPORTED);
    }
    if (weChatReceiver == null) {
      weChatReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
          int errCode = intent.getIntExtra("errCode", -1);
          String code = intent.getStringExtra("code");
          String state = intent.getStringExtra("state");
          Log.i("WeChatHelper", "weChatReceiver: 收到微信回调 - errCode: " + errCode + ", code: " + code + ", state: " + state);
          if (channel != null) {
            // 将参数放入 Map
            Map<String, Object> args = new HashMap<>();
            args.put("errCode", errCode);
            args.put("code", code);
            args.put("state", state);
            Log.i("WeChatHelper", "weChatReceiver: 调用Flutter方法 onWeChatResponse");
            channel.invokeMethod("onWeChatResponse", args);
          } else {
            Log.e("WeChatHelper", "weChatReceiver: channel为null，无法调用Flutter方法");
          }
        }
      };
      IntentFilter filter = new IntentFilter("com.tencent.mm.opensdk.WECHAT_CALLBACK");
      ContextCompat.registerReceiver(context, weChatReceiver, filter, ContextCompat.RECEIVER_NOT_EXPORTED);
      Log.i("WeChatHelper", "init: 注册微信回调接收器");
    }
    Log.i("WeChatHelper", "init: 初始化完成");
  }

  public static void updateChannel(MethodChannel newChannel) {
    channel = newChannel;
  }

  public static boolean isWeChatInstalled() {
    boolean installed = api != null && api.isWXAppInstalled();
    Log.i("WeChatHelper", "isWeChatInstalled: " + installed);
    return installed;
  }

  public static boolean login() {
    Log.i("WeChatHelper", "login: 开始微信登录");
    if (api == null) {
      Log.e("WeChatHelper", "login: api为null，无法登录");
      return false;
    }
    SendAuth.Req req = new SendAuth.Req();
    req.scope = "snsapi_userinfo";
    req.state = "wechat_sdk_login_state";
    boolean result = api.sendReq(req);
    Log.i("WeChatHelper", "login: 发送登录请求，结果: " + result);
    return result;
  }

  public static void handleIntent(Context context, Intent intent, IWXAPIEventHandler handler) {
    if (api == null) {
      api = WXAPIFactory.createWXAPI(context, APP_ID, false);
    }
    api.handleIntent(intent, handler);
  }

  @SuppressLint("UnprotectedReceiver")
  @SuppressWarnings("PatternVariableCanBeUsed")
  public static void broadcastResponse(Context context, BaseResp resp) {
    Log.i("WeChatHelper", "broadcastResponse: 开始广播微信响应");
    if (context == null) {
      Log.e("WeChatHelper", "broadcastResponse: context is null");
      return;
    }
    Intent intent = new Intent("com.tencent.mm.opensdk.WECHAT_CALLBACK");
    intent.putExtra("errCode", resp.errCode);
    intent.putExtra("type", resp.getType());
    if (resp instanceof SendAuth.Resp) {
      SendAuth.Resp authResp = (SendAuth.Resp) resp;
      intent.putExtra("code", authResp.code);
      intent.putExtra("state", authResp.state);
      Log.i("WeChatHelper", "broadcastResponse: 发送授权响应 - errCode: " + resp.errCode + ", code: " + authResp.code + ", state: " + authResp.state);
    } else {
      Log.i("WeChatHelper", "broadcastResponse: 发送非授权响应 - errCode: " + resp.errCode + ", type: " + resp.getType());
    }
    String packageName = context.getPackageName();
    Log.i("WeChatHelper", "Setting package name: " + packageName);
    intent.setPackage(packageName);
    context.sendBroadcast(intent);
    Log.i("WeChatHelper", "broadcastResponse: 广播已发送");
  }

  public static void cleanup(Context context) {
    if (weChatReceiver != null) {
      context.unregisterReceiver(weChatReceiver);
      weChatReceiver = null;
    }
    if (refreshReceiver != null) {
      context.unregisterReceiver(refreshReceiver);
      refreshReceiver = null;
    }
    api = null;
    channel = null;
  }
}